from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_job
import logging

from django_apscheduler.models import DjangoJob

from apis.base_data.management.commands.exp_statistics import Command

logger = logging.getLogger(__name__)

# 注释掉 APScheduler 启动代码以避免数据库表不存在的错误
# scheduler = BackgroundScheduler()
# scheduler.add_jobstore(DjangoJobStore(), "default")

# try:

#     def daily_task():
#         command_group = Command()
#         command_group.handle()


#     # 假设你要添加的任务名称为 'daily_task'
#     job_id = 'daily_task_bendi'
#     if not DjangoJob.objects.filter(id=job_id).exists():
#         # 如果任务不存在，则添加新任务
#         print(f"任务 '{job_id}' 添加任务。")
#         # scheduler.add_job(daily_task, 'interval', minutes=10, id='daily_task')
#         scheduler.add_job(daily_task, trigger='cron', hour=1, id=job_id)
#     else:
#         # 打印调度器中所有任务的 id
#         all_jobs = scheduler.get_jobs()
#         job_ids = [job.id for job in all_jobs]
#         print(f"All job IDs in scheduler: {job_ids}")
#         if job_id in job_ids:
#             scheduler.modify_job(job_id=job_id, trigger='cron', hour=1)
#             print(f"任务 '{job_id}' 已存在，已更新定时任务。")
#         else:
#             job = DjangoJob.objects.get(id=job_id)
#             job.delete()
#             print(f"任务 '{job_id}' 任务删除。")
#             scheduler.add_job(daily_task, trigger='cron', hour=1, id=job_id)
#             print(f"任务 '{job_id}' 任务添加后启动。")
#     scheduler.start()
# except Exception as e:
#     logger.error(f"Error starting scheduler: {e}")
#     scheduler.shutdown()
